//
//  GridTreeNodeViewController.swift
//  grid-ios-app
//
//  Created by wondertek on 2024/5/20.
//

import UIKit
import ObjectMapper
import SnapKit

class GridTreeNodeViewController: GridBaseViewController {

    var allNodes :[GridTreeNodeModel] = []
//    var listArr :[GridTreeNodeModel] = []
    var mNodes: [GridTreeNodeModel]? //可见的node

    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = " 树形结构"
        // Do any additional setup after loading the view.
        // 模拟数据，数据结构看tree.json
        let listArr = self.mockData()
        allNodes = GridTreeNodeHelper.shared.getSortedNodes(listArr)
        mNodes = GridTreeNodeHelper.shared.filterVisibleNode(listArr)
        
        tableView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(0)
            make.left.right.bottom.equalToSuperview()
        }
    }
    
    public  func mockData() -> [GridTreeNodeModel]{
        let trees = [GridTreeNodeModel]()
        do{
            let data = try Data(contentsOf: Bundle.main.url(forResource: "tree.json", withExtension: nil)!)
            print(data)

            guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [[String: Any]] else{
                return trees
            }
            print(jsonArray)

            let modelList = Mapper<GridTreeNodeModel>().mapArray(JSONArray: jsonArray)
            return modelList
        }catch{
            fatalError("JSON数据解析失败")
        }
        return trees
    }
    

    lazy var tableView: UITableView = {
        let tv = UITableView.init(frame: CGRect.zero, style: .plain)
        tv.backgroundColor = .white
        tv.separatorStyle = .none
        tv.delegate = self
        tv.dataSource = self
        tv.register(GridTreeNodeTableViewCell.self, forCellReuseIdentifier: "GridTreeNodeTableViewCell")
        view.addSubview(tv)
        return tv
    }()
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    

}

extension GridTreeNodeViewController: UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 通过nib自定义tableviewcell
        let cell = tableView.dequeueReusableCell(withIdentifier: "GridTreeNodeTableViewCell", for: indexPath) as! GridTreeNodeTableViewCell
       
        cell.cellModel =  mNodes![indexPath.row]
        cell.indexPath = indexPath
        cell.delegate = self
        return cell
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (mNodes?.count)!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 55.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let parentNode = mNodes![indexPath.row]
        // 点击选中
        print("选中id：\(parentNode.id ?? "") 选中name：\(parentNode.companyName ?? "")")
        
    }
    
    //展开或者关闭某个节点
    func expandOrCollapse(_ count: inout Int, node: GridTreeNodeModel) {
        if node.isExpand { //如果当前节点是开着的，需要关闭节点下的所有子节点
            closedChildNode(&count,node: node)
        } else { //如果节点是关着的，打开当前节点即可
            if let children = node.children {
                count += children.count
                node.setExpand(true)
            }
          
        }
        
    }
    
    //关闭某个节点和该节点的所有子节点
    func closedChildNode(_ count:inout Int, node: GridTreeNodeModel) {
        if node.isLeaf() {
            return
        }
        if node.isExpand {
            node.isExpand = false
            if let children = node.children {
                for item in children { //关闭子节点
                    count += 1 // 计算子节点数加一
                    closedChildNode(&count, node: item)
                }
            }
            
        }
    }
}

extension GridTreeNodeViewController: GridTreeNodeTableViewCellDelegate {
    func gridTreeNodeTableViewCellMergeClick(_ indexPath: IndexPath) {
        if indexPath.row >= 0 && indexPath.row < mNodes!.count {
            let parentNode = mNodes![indexPath.row]
            
            let startPosition = indexPath.row+1
            var endPosition = startPosition
            
            if parentNode.isLeaf() {// 点击的节点为叶子节点
                // do something
            } else {
               
                //  更新展开信息
                expandOrCollapse(&endPosition, node: parentNode)
                //更新可见节点
                mNodes = GridTreeNodeHelper.shared.filterVisibleNode(allNodes)
                
                //修正indexpath
                var indexPathArray :[IndexPath] = []
                var tempIndexPath: IndexPath?
                for i in startPosition ..< endPosition {
                    tempIndexPath = IndexPath(row: i, section: 0)
                    indexPathArray.append(tempIndexPath!)
                }
                
                // 插入和删除节点的动画
                if parentNode.isExpand {
                    self.tableView.insertRows(at: indexPathArray, with: UITableView.RowAnimation.none)
                } else {
                    self.tableView.deleteRows(at: indexPathArray, with: UITableView.RowAnimation.none)
                }
                //更新被选组节点
//                self.tableView.reloadRows(at: [indexPath], with: UITableView.RowAnimation.none)
                self.tableView.reloadData()

            }
        }
    }
}

